﻿using System.Configuration;
using System.IO;
using System.Web;

namespace Ledict.Utility.Helper
{
    /// <summary>
    /// Config配置文件 公共帮助类
    /// 版本：2.0
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key">key</param>
        public static string AppSettings(string key)
        {
            var strValue = ConfigurationManager.AppSettings[key];
            return string.IsNullOrEmpty(strValue) ? string.Empty : strValue.Trim();

        }
        /// <summary>
        /// 根据name取connectionString值
        /// </summary>
        /// <param name="name"></param>
        public static ConnectionStringSettings ConnectionStrings(string name)
        {

            return ConfigurationManager.ConnectionStrings[name];

        }
        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="filePath">/XmlConfig/Config.xml</param>
        /// <param name="node">//appSettings</param>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string filePath, string node, string key, string value, string type)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            string path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, filePath);
            xDoc.Load(path);
            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode(node);

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@" + type + "='" + key + "']");
            if (xElem1 != null)
            {
                if (type == "key")
                {
                    xElem1.SetAttribute("value", value);
                }
                else
                {
                    xElem1.SetAttribute("connectionString", value);
                }
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", key);
                if (type == "key")
                {
                    xElem2.SetAttribute("value", value);
                }
                else
                {
                    xElem1.SetAttribute("connectionString", value);
                }
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(path);
        }
    }
}
